<template>
  <div class="medical-card-management">
    <!-- 搜索区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="医疗卡号">
          <el-input
            v-model="queryParams.cardNumber"
            placeholder="请输入医疗卡号"
            clearable
          />
        </el-form-item>
        <el-form-item label="保险类型">
          <el-select
            v-model="queryParams.insuranceType"
            placeholder="请选择保险类型"
            clearable
            style="width: 110px"
          >
            <el-option label="职工医保" value="职工医保" />
            <el-option label="居民医保" value="居民医保" />
          </el-select>
        </el-form-item>
        <el-form-item label="病人姓名">
          <el-input
            v-model="queryParams.insureName"
            placeholder="请输入"
            clearable
            style="width: 110px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 80px"
          >
            <el-option label="有效" :value="1" />
            <el-option label="无效" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'medical:card:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button
          type="primary"
          v-permission="'medical:card:add'"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>新增医疗卡
        </el-button>
      </div>
    </div>

    <!-- 医疗卡表格 -->
    <el-table
      :data="medicalCardList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="cardNumber" label="医疗卡号" width="180" />
      <el-table-column prop="insureName" label="病人姓名" width="120" />
      <el-table-column prop="insuranceType" label="保险类型" width="120" />
      <el-table-column prop="issueDate" label="发卡日期" width="120" />
      <el-table-column prop="expiryDate" label="到期日期" width="120" />
      <el-table-column prop="hospitalName" label="定点医院" width="200" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-permission="'medical:card:edit'"
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
            v-permission="'medical:card:edit'"
            size="small"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'medical:card:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="medicalCardForm"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="病人姓名" prop="insureId">
          <el-select
            v-model="formData.insureId"
            filterable
            remote
            reserve-keyword
            placeholder="病人姓名- 输入关键字进行搜索"
            :remote-method="searchInsure"
            :loading="userLoading"
          >
            <el-option
              v-for="user in insureOptions"
              :key="user.id"
              :label="`${user.insureName}    电话: ${user.phone}    身份证: ${user.idCard}`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医疗卡号" prop="cardNumber">
          <el-input
            v-model="formData.cardNumber"
            placeholder="请输入医疗卡号"
          />
        </el-form-item>
        <el-form-item label="保险类型" prop="insuranceType">
          <el-select
            v-model="formData.insuranceType"
            placeholder="请选择保险类型"
          >
            <el-option label="职工医保" value="职工医保" />
            <el-option label="居民医保" value="居民医保" />
          </el-select>
        </el-form-item>
        <el-form-item label="发卡日期" prop="issueDate">
          <el-date-picker
            v-model="formData.issueDate"
            type="date"
            placeholder="选择发卡日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="expiryDate">
          <el-date-picker
            v-model="formData.expiryDate"
            type="date"
            placeholder="选择到期日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="定点医院" prop="hospitalId">
          <el-select
            v-model="formData.hospitalId"
            filterable
            placeholder="请选择定点医院"
          >
            <el-option
              v-for="hospital in hospitalOptions"
              :key="hospital.id"
              :label="hospital.name"
              :value="hospital.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="0">无效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getMedicalCardPage,
  addMedicalCard,
  updateMedicalCard,
  deleteMedicalCard,
  changeMedicalCardStatus
} from '@/api/medicalCard'
import { getInsureList } from '@/api/insure'
import { listAllHospitals } from '@/api/hospital'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  cardNumber: '',
  insuranceType: '',
  insureName: '',
  status: null
})

// 表格数据
const medicalCardList = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  id: null,
  insureId: null,
  cardNumber: '',
  insuranceType: '',
  issueDate: '',
  expiryDate: '',
  hospitalId: null,
  status: 1,
  insureName: ''
})

// 病人搜索选项
const insureOptions = ref([])
const userLoading = ref(false)

// 医院选项
const hospitalOptions = ref([])

// 表单验证规则
const rules = reactive({
  insureId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  cardNumber: [{ required: true, message: '请输入医疗卡号', trigger: 'blur' }],
  insuranceType: [
    { required: true, message: '请选择保险类型', trigger: 'change' }
  ],
  issueDate: [{ required: true, message: '请选择发卡日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

// 获取医疗卡列表
const fetchMedicalCardList = async () => {
  try {
    loading.value = true
    const res = await getMedicalCardPage(queryParams)
    medicalCardList.value = res.data.data.records
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}
// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
// 搜索病人
const searchInsureRaw = async (query) => {
  if (query !== '') {
    userLoading.value = true
    try {
      const res = await getInsureList({
        page: 1,
        pageSize: 10000,
        insureName: query
      })
      console.log('搜索病人返回数据:', res.data.data.records)
      insureOptions.value = res.data.data.records
    } finally {
      userLoading.value = false
    }
  } else {
    insureOptions.value = []
  }
}
// 使用防抖包装搜索方法
const searchInsure = debounce(searchInsureRaw, 300)
// 获取所有医院
const fetchAllHospitals = async () => {
  const res = await listAllHospitals()
  hospitalOptions.value = res.data.data
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchMedicalCardList()
}

// 重置搜索
const resetQuery = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    cardNumber: '',
    insuranceType: '',
    insureName: '',
    status: null
  })
  fetchMedicalCardList()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchMedicalCardList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchMedicalCardList()
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await changeMedicalCardStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增医疗卡
const handleAdd = () => {
  dialogTitle.value = '新增医疗卡'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑医疗卡
const handleEdit = (row) => {
  dialogTitle.value = '编辑医疗卡'
  isAdd.value = false
  console.log('编辑行数据:', row)
  // 先清空表单数据
  resetForm()
  // 然后赋值
  Object.assign(formData, row)
  // 确保insureId正确赋值
  formData.insureId = row.insureId
  dialogVisible.value = true
}

// 删除医疗卡
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该医疗卡吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteMedicalCard(row.id)
      ElMessage.success('删除成功')
      fetchMedicalCardList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    insureId: null,
    cardNumber: '',
    insuranceType: '',
    issueDate: '',
    expiryDate: '',
    hospitalId: null,
    status: 1,
    insureName: ''
  })
  insureOptions.value = []
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addMedicalCard(formData)
      ElMessage.success('新增成功')
    } else {
      await updateMedicalCard(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchMedicalCardList()
  } catch (error) {
    console.error(error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchMedicalCardList()
  fetchAllHospitals()
})
</script>

<style scoped>
.medical-card-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
